/**
 * author:Administrator
 * date:2016/1/4
 * desc: koa-better-body in router
 */

'use strict';

var bodyParser = require('koa-better-body');
var koaBody = bodyParser({});

var Router = require('koa-router');
var __pathPrefix = '/accounts';
var router = new Router({prefix: __pathPrefix});
module.exports = router.routes();

var biz = require('../biz/account.js');
/**
 * post /accounts
 {
   "name": "wzq",
   "money": 12.34
 }
 */
router.post('/', koaBody, function*() {
  var json = {
    name: this.request.body.fields.name,
    money: this.request.body.fields.money
  };
  console.log(json);
  var retObj = yield biz.create(json);
  console.log(retObj);
  this.body = retObj;
});

/**
 * 进行transaction
 * post /accounts/transaction
 {
    "from":xx,
    "to":xx,
    "money":123
 }
 */
router.post('/transaction', koaBody, function*() {
  var from = this.request.body.fields.from;
  var to = this.request.body.fields.to;
  var money = this.request.body.fields.money;
  // TODO check money > 0
  var retObj = yield biz.transaction(from, to, money);
  console.log(retObj);
  this.body = retObj;
});

/**
 * 获取某个账户信息
 */
router.get('/:id', function*() {
  var id = this.params.id;
  var retObj = yield  biz.get(id);
  console.log(retObj);
  this.body = retObj;
});

/**
 * 修改
 {"name":"xx","money":"xx"}
 */
router.put('/:id', koaBody, function*() {
  var id = this.params.id;
  var name = this.request.body.fields.name;
  var money = this.request.body.fields.money;
  var retObj = yield biz.update(id, name, money);
  console.log(retObj);
  this.body = retObj;
});

router.delete('/:id', function*() {
  var id = this.params.id;
  var retObj = yield biz.delete(id);
  console.log(retObj);
  this.body = retObj;
});